package api.action;

import api.model.ApiAuthInter;
import api.model.ApiTable;
import api.service.ApiAuthInterService;
import com.alibaba.fastjson.JSONObject;
import m.common.action.ActionMeta;
import m.common.action.RequestMeta;
import m.common.action.VueResult;
import m.common.model.util.ModelQueryList;
import m.common.model.util.QueryCondition;
import m.html.VueFormResult;
import m.html.element.Element;
import m.html.element.other.DisplayItem;
import m.html.form.*;
import m.system.cache.CacheUtil;
import m.system.exception.MException;
import m.system.handler.HandlerUtil;
import m.system.util.JSONMessage;
import m.system.util.ObjectUtil;
import m.system.util.StringUtil;
import manage.action.StatusAction;
import manage.util.DictionaryUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@ActionMeta(name="api/apiAuthInter")
public class ApiAuthInterAction extends StatusAction {
    private ApiAuthInter model;

    public JSONMessage doSave() throws Exception {
        systemLog("鉴权","保存鉴权接口");
        verifyAdminOperPower(getStatusPower());
        String msg=getService(ApiAuthInterService.class).save(model);
        return new JSONMessage(0,msg)
                .push("model", model);
    }
    public VueResult toEdit() throws Exception {
        verifyMenu("A2111");
        verifyAdminOperPower(getStatusPower());
        if(null!=model&&!StringUtil.isSpace(model.getName())&&!StringUtil.isSpace(model.getAuth().getName())){
            model=getService(ApiAuthInterService.class).get(model.getAuth().getAuthId(),model.getName());
        }else if(null!=model&& ObjectUtil.notEmptyOid(model.getAuth())){
            model.setType("B");
        }else{
            throw new MException(this.getClass(),"参数错误");
        }

        ModelForm form = new ModelForm("鉴权接口信息",2);
        form.addItem(
            FormInput.radio("类型", "model.type", "api.model.ApiAuthInter!type"),
            FormInput.input("名称", "model.name").setPlaceholder("请输入名称|小写英文或下划线"),
            FormInput.input("描述", "model.description").setPlaceholder("请输入描述").setSpan(2),
            FormInput.select("接口模型","model.modelTable.oid","'api.model.ApiTable:'+(model.type=='A'?'N':'')").setSpan(2).setPlaceholder("请选择接口模型"),
            FormTest.test("model.type!='A'",
                FormInput.selectItem("扩展属性", "model.subTables","'"+actionUrl(ApiColumnAction.class,"getModelColumnOption")+"?tableOid='+model.modelTable.oid",true).setSpan(2).setPlaceholder("请输入扩展属性")
            ),
            FormInput.selectItem("数据处理","model.dataHandler","'action/api/apiAuthInter/getDataHandlerOptions?tableOid='+model.modelTable.oid",true).setSpan(2).setPlaceholder("请选择数据处理")
        )
        .addData("model",model)
        .addWatch("model.modelTable.oid","this.model.subTables=[];delete this.model.dataHandler;")
        .addButton(
            FormButton.pri("保存","doSave")
        )
        .addMethod(
            FormEvent.backFlag,
            FormEvent.doJson("doSave",actionUrl("doSave"),"{model:this.model}")
                .success("backFlag")
        );
        VueFormResult result=new VueFormResult();
        return result.addForm(form)
            .addForm(
                new CustomForm("提示",false)
                .addElement(Element.tag("a-alert").A("message","导入时，数据在更新前调用数据处理方法；查询时，数据在查询后调用数据处理方法。"))
            );
    }
    @RequestMeta(params = {"tableOid"})
    public JSONMessage getDataHandlerOptions(String tableOid) throws Exception {
        List<DisplayItem> dhList= new ArrayList<>();
        ApiTable at=ModelQueryList.getModel(ApiTable.class,tableOid,"*");
        if(null!=at&&StringUtil.notSpace(at.getSourceClass())){
            Map<String,String> hMap= HandlerUtil.getAllHandler(at.getSourceClass());
            hMap.forEach((k,v)->{dhList.add(DisplayItem.value(k,v));});
        }else{
            Map<String,String> hMap= HandlerUtil.getAllHandler(String.valueOf(JSONObject.class));
            hMap.forEach((k,v)->{dhList.add(DisplayItem.value(k,v));});
        }
        return DictionaryUtil.toDictData(dhList);
    }
    @RequestMeta(params = {"authOid"})
    public JSONMessage getList(String authOid) throws Exception {
        verifyAdminOperPower(getStatusPower());
        return new JSONMessage(0)
                .push("list",
                    ModelQueryList.getModelList(ApiAuthInter.class,
                        new String[]{"*","auth.authId"},null,
                        QueryCondition.eq("auth.oid",authOid)
                    )
                );
    }
    @RequestMeta(params = {"authId","name"})
    public JSONMessage getParamExample(String authId,String name) throws Exception {
        verifyAdminOperPower(getStatusPower());
        return new JSONMessage(0)
                .push("example",getService(ApiAuthInterService.class).getParamExample(authId,name));
    }

    @Override
    public void doRecoveryCallback() throws Exception {
        model= ModelQueryList.getModel(model,"auth.authId","name");
        CacheUtil.clear(ApiAuthInter.class,model.getAuth().getAuthId(),model.getName());
    }

    @Override
    public void doDisableCallback() throws Exception {
        model= ModelQueryList.getModel(model,"auth.authId","name");
        CacheUtil.clear(ApiAuthInter.class,model.getAuth().getAuthId(),model.getName());
    }
    @Override
    public ApiAuthInter getModel() {
        return model;
    }

    public void setModel(ApiAuthInter model) {
        this.model = model;
    }

    @Override
    public String[] getStatusPower() {
        return new String[]{"manage_api_power"};
    }
}
